package com.sun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.BaseContext;
import com.sun.common.Result;
import com.sun.common.SystemCrmlog;
import com.sun.entity.Drug;
import com.sun.entity.Problem;
import com.sun.entity.Store;
import com.sun.service.DrugService;
import com.sun.service.ProblemService;
import com.sun.service.StoreService;
import com.sun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/3/22 14:24
 * @FileName: StoreController
 * @Description: "库存管理"
 */
@RestController
@RequestMapping("/store")
public class StoreController {
    @Autowired
    private StoreService storeService;

    @Autowired
    private DrugService drugService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProblemService problemService;

    /**
     * 修改库存信息
     *
     * @param store
     * @return
     */
    @SystemCrmlog(title = "库存管理模块", type = "UPDATE", description = "修改库存信息")
    @PutMapping
    public Result<String> update(@RequestBody Store store) {
        storeService.updateById(store);
        return Result.success("库存信息修改成功");
    }

    /**
     * 库存盘点
     *
     * @param store
     * @return
     */
    @SystemCrmlog(title = "库存管理模块", type = "UPDATE", description = "库存盘点")
    @PutMapping("/inventoryCount")
    public Result<String> inventoryCount(@RequestBody Store store) {
        int flag = 0;
        if (store.getDrugNumber().toString().equals(store.getInventory())) {
            flag = 1;
        }
        store.setCorrect(flag);
        Long currentId = BaseContext.getCurrentId();
        String userName = userService.selcetUserName(currentId);
        store.setChecked(userName);
        storeService.updateById(store);
        return Result.success("库存信息修改成功");
    }

    /**
     * 查询出所有的库存数不（不为0的可以库存盘点，为0的可以删除）
     */
    @GetMapping
    public Result<Page> select(int pageNum, int pageSize, String drugName, String drugCode, String addr,
                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        //分页构造器对象
        Page<Store> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(drugName != null, Store::getDrugName, drugName);
        lambdaQueryWrapper.like(drugCode != null, Store::getDrugCode, drugCode);
        lambdaQueryWrapper.like(addr != null, Store::getAddr, addr);
        lambdaQueryWrapper.gt(startTime != null, Store::getIntime, startTime).lt(endTime != null, Store::getIntime, endTime);

        storeService.page(pageInfo, lambdaQueryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 查询出已经过期的库存药品
     *
     * @param
     * @return
     */
    @GetMapping("/findExpiredMedicines")
    public Result<List<Store>> findExpiredMedicines() {
        LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.lt(Store::getUsefulDate, LocalDateTime.now());
        lambdaQueryWrapper.ne(Store::getDrugNumber, 0);
        List<Store> storeList = storeService.list(lambdaQueryWrapper);


        return Result.success(storeList);
    }

    /**
     * 把这些药品插入到问题药品表中，并把这些药品的数量置为0
     *
     * @param
     * @return
     */
    @SystemCrmlog(title = "库存管理模块", type = "UPDATE", description = "药品报损")
    @Transactional
    @PostMapping("/handleExpired")
    public Result<String> handleExpired(@RequestBody List<Store> stores) {
        List<Problem> problems = new ArrayList<>();
        for (int i = 0; i < stores.size(); i++) {
            Store store = stores.get(i);
            Problem problem = new Problem();
            problem.setDrugId(store.getDrugId());
            problem.setDrugName(store.getDrugName());
            problem.setDrugCode(store.getDrugCode());
            problem.setDrugCount(store.getDrugNumber());
            problem.setDrugPrice(store.getInprice());
            problem.setReason("药品过期了");
            problem.setCreateTime(LocalDateTime.now());
            problems.add(problem);

            store.setDrugNumber(0);
        }


        problemService.saveBatch(problems);


        storeService.updateBatchById(stores);

        return Result.success("操作成功");
    }

    /**
     * 查询药品现有库存 是否正确
     *
     * @param
     * @return
     */
    @GetMapping("/inventory")
    public Result<Page> inventoryQuery(int pageNum, int pageSize, String drugName, String drugCode, Long categoryId) {
        List<Store> result = new ArrayList<>();
        Page<Store> pageInfo = new Page<>();
        LambdaQueryWrapper<Drug> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        //添加过滤条件
        //根据药品名称
        lambdaQueryWrapper1.like(null != drugName, Drug::getDrugName, drugName);
        //根据药品代码
        lambdaQueryWrapper1.like(null != drugCode, Drug::getDrugCode, drugCode);
        //根据药品分类
        lambdaQueryWrapper1.eq(null != categoryId, Drug::getCategoryId, categoryId);
        lambdaQueryWrapper1.orderByAsc(Drug::getDrugName);
        List<Drug> drugList = drugService.list(lambdaQueryWrapper1);
        for (Drug drug : drugList) {
            Store store = new Store();
            LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Store::getDrugId, drug.getDrugId());
            List<Store> stores = storeService.list(lambdaQueryWrapper);
            if (stores.isEmpty()) {
                store.setDrugId(drug.getDrugId());
                store.setDrugName(drug.getDrugName());
                store.setDrugCode(drug.getDrugCode());
                store.setDrugNumber(0);
                store.setSingleunit("盒");
                store.setOutprice("0");
            } else {
                int num = 0;
                String singLeunit = "";
                String outprice = "0";
                for (int i = 0; i < stores.size(); i++) {
                    num = num + stores.get(i).getDrugNumber();
                    outprice = stores.get(i).getOutprice();
                    singLeunit = stores.get(i).getSingleunit();
                }
                store.setDrugId(drug.getDrugId());
                store.setDrugName(drug.getDrugName());
                store.setDrugCode(drug.getDrugCode());
                store.setDrugNumber(num);
                store.setSingleunit(singLeunit);
                store.setOutprice(outprice);
            }
            result.add(store);
        }
        pageInfo.setTotal(result.size());
        pageInfo.setSize(pageSize);
        pageInfo.setCurrent(pageNum);
        List<Store> stores = new ArrayList<>();
        if (result.size() > (pageNum - 1) * pageSize + pageSize) {
            stores = result.subList((pageNum - 1) * pageSize, (pageNum - 1) * pageSize + pageSize);
        } else {
            stores = result.subList((pageNum - 1) * pageSize, result.size());
        }
        pageInfo.setRecords(stores);
        return Result.success(pageInfo);
    }

    /**
     * 根据id删除库存记录
     */
    @SystemCrmlog(title = "库存管理模块", type = "DELETE", description = "根据id删除库存记录")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        Store store = storeService.getById(id);
        if (store.getDrugNumber() > 0) {
            return Result.error("该记录还有库存，不能删除");
        }
        storeService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 查询盘点数据
     */
    @GetMapping("/getInventoryData")
    public Result<Page> getInventoryData(int pageNum, int pageSize, String drugName, String drugCode, String addr,
                                         String checked,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Page<Store> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.isNotNull(Store::getInventory);
        lambdaQueryWrapper.like(drugName != null, Store::getDrugName, drugName);
        lambdaQueryWrapper.like(drugCode != null, Store::getDrugCode, drugCode);
        lambdaQueryWrapper.like(addr != null, Store::getAddr, addr);
        lambdaQueryWrapper.like(checked != null, Store::getChecked, checked);
        lambdaQueryWrapper.gt(startTime != null, Store::getIntime, startTime).lt(endTime != null, Store::getIntime, endTime);
        storeService.page(pageInfo, lambdaQueryWrapper);
        return Result.success(pageInfo);
    }

}
